<?php

namespace app\api\controller;

use app\api\model\WxUser;
use think\response\Json;

class Site
{
    public function getMiniOpenid(): object
    {
        // 接收参数
        $js_code = request()->post('js_code', '');
        if (empty($js_code)) errMsg('请上传code');
        //解密code
        $wechat = new \app\api\model\Wechat();
        $res = $wechat->getOpenid($js_code);
        if (isset($res['openid'])) {
            //检测变量是否存在、
            $wxuser = new WxUser();
            $model = $wxuser->where('mini_openid', $res['openid'])->findOrEmpty()->toArray();
            if (empty($model)) {
                //新增用户信息
                $resSave = $wxuser->save([
                    'mini_openid' => $res['openid'],
                    'mini_session_key' => $res['session_key'],
                ]);
                return successMsg([
                    'openid' => $res['openid'],
                ], 1, '获取成功');
            } else {
                //修改用户信息
                $resSave = $wxuser->where('id', $model['id'])->save([
                    'mini_openid' => $res['openid'],
                    'mini_session_key' => $res['session_key'],
                ]);
                if ($resSave !== false) return successMsg([
                    'openid' => $res['openid'],
                ], 1, '获取成功');
                return errMsg('登录失败');
            }
        }
        return errMsg('登录失败');
    }
}